package api

import (
	"enjoy_wys/internal/model"
	"enjoy_wys/internal/server"
	"enjoy_wys/pkg"
	"enjoy_wys/routerquest"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func Register(c *gin.Context) {
	var Add routerquest.Register
	if err := c.ShouldBindJSON(&Add); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	res := model.Register{
		Username: Add.Username,
		Password: Add.Password,
		Mobile:   Add.Mobile,
	}
	err := server.AddUser(&res)
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "注册成功", "data": res})
}
func Login(c *gin.Context) {
	var res routerquest.Login
	if err := c.ShouldBindJSON(&res); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	stu := model.Register{
		Username: res.Username,
	}
	err := server.GetUserInfo(&stu)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": http.StatusBadRequest, "msg": "用户名不存在"})
		return
	}
	if stu.Password != res.Password {
		c.JSON(http.StatusBadRequest, gin.H{"code": http.StatusBadRequest, "msg": "密码错误"})
		return
	}
	CustomClaims := pkg.CustomClaims{
		ID: stu.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400,
		},
	}
	token, err := pkg.NewJWT("2206A").CreateToken(CustomClaims)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": http.StatusBadRequest, "msg": "登录失败"})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "msg": "登录成功", "data": token})
	}
}
